package com.example.aircraftwar.startgame;

import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.aircraftwar.R;
import com.example.aircraftwar.application.game.Game;
import com.example.aircraftwar.application.MainActivity;
import com.example.aircraftwar.application.MusicService;
import com.example.aircraftwar.application.loginorregister.LoginOrRegisterActivity;
import com.example.aircraftwar.application.network.NetConn;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import java.io.IOException;
import java.util.Objects;

public class StartGameActivity extends AppCompatActivity {
    public static int selectPattern;
    private String pattern;
    public static boolean isPlay = true;
    private static Button easyButton;
    private static Button hardButton;
    private static Button normalButton;
    private static Switch musicSwitch;
    private Intent intent;
    private static Game game;

    public static MusicService.MyBinder myBinder;
    private Connect conn;

    private ProgressDialog dialog;

//    public StartGame() {
//        super();
//    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start_game);
        easyButton = findViewById(R.id.easygame);
        easyButton.setBackgroundResource(R.drawable.button);
        normalButton = findViewById(R.id.normalgame);
        normalButton.setBackgroundResource(R.drawable.button);
        hardButton = findViewById(R.id.hardgame);
        hardButton.setBackgroundResource(R.drawable.button);
        musicSwitch = findViewById(R.id.music);
//        intent = new Intent(StartGame.this,Game.class);

        easyButton.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if(motionEvent.getAction() == MotionEvent.ACTION_DOWN){
                    easyButton.setBackgroundResource(R.drawable.buttonclick);
                }else if(motionEvent.getAction() == MotionEvent.ACTION_UP){
                    easyButton.setBackgroundResource(R.drawable.button);
                    selectPattern = 1;
                    if (MainActivity.isonline) {
                        changepattern();
                    } else {
                        gameactivity();
                    }
                }
                return false;
            }
        });
        normalButton.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if(motionEvent.getAction() == MotionEvent.ACTION_DOWN){
                    normalButton.setBackgroundResource(R.drawable.buttonclick);
                }else if(motionEvent.getAction() == MotionEvent.ACTION_UP){
                    normalButton.setBackgroundResource(R.drawable.button);
                    selectPattern = 2;
                    if (MainActivity.isonline) {
                        changepattern();
                    } else {
                        gameactivity();
                    }
                }
                return false;
            }
        });
        hardButton.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if(motionEvent.getAction() == MotionEvent.ACTION_DOWN){
                    hardButton.setBackgroundResource(R.drawable.buttonclick);
                }else if(motionEvent.getAction() == MotionEvent.ACTION_UP){
                    hardButton.setBackgroundResource(R.drawable.button);
                    selectPattern = 3;
                    if (MainActivity.isonline) {
                        changepattern();
                    } else {
                        gameactivity();
                    }
                }
                return false;
            }
        });
        musicSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    isPlay = true;
                }
                else {
                    isPlay = false;
                }
            }
        });
        Log.i("music demo","bind service");
        conn = new Connect();
        intent = new Intent(this, MusicService.class);
        bindService(intent,conn, Context.BIND_AUTO_CREATE);

        if (MainActivity.isonline) {
            dialog = new ProgressDialog(this);
            dialog.setMessage("正在匹配另一位玩家...");
            dialog.show();
            dialog.setCanceledOnTouchOutside(false);

        new Thread(ready).start();
        }
    }

    private JSONObject initJson(String request,String userName, String pattern) throws JSONException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("request", request);
        jsonObject.put("username", userName);
        jsonObject.put("selectpattern", pattern);
        return jsonObject;
    }

    private void changepattern() {
        if (selectPattern == 1) {
            pattern = "easy";
        } else if (selectPattern == 2) {
            pattern = "normal";
        } else {
            pattern = "hard";
        }
        //向服务器发送用户名和难度选择
//        new Thread(() -> NetConn.writer.println("changepattern")).start();
        new Thread(() -> {
            try {
                System.out.println(pattern);
                NetConn.writer.println(initJson("changepattern",LoginOrRegisterActivity.userName,pattern).toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }).start();
    }

    Runnable ready = () -> {
        String reply = "";
        try {
            while ((reply = NetConn.reader.readLine()) != null) {
                System.out.println(reply);
                JSONObject jsonObject = JSONObject.fromObject(reply);
                reply = jsonObject.getString("msg");
                if (reply.equals("choosepattern")) {
                    dialog.dismiss();
                } else if (reply.equals("startgame")) {
                    gameactivity();
                } else if (reply.equals("select")) {
                    String username = jsonObject.getString("username");
                    String pattern = jsonObject.getString("selectpattern");
                    if (!Objects.equals(username, LoginOrRegisterActivity.userName)) {
                        runOnUiThread(() -> {
                            if (pattern.equals("easy")) {
                                Toast.makeText(this, "对方选择了简单模式", Toast.LENGTH_SHORT).show();
                            } else if (pattern.equals("normal")) {
                                Toast.makeText(this, "对方选择了普通模式", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(this, "对方选择了困难模式", Toast.LENGTH_SHORT).show();
                            }

                        });
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    };

    class Connect implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service){
            Log.i("music demo","Service Connnected");
            myBinder = (MusicService.MyBinder)service;
        }
        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i("music demo","stop");
        unbindService(conn);
    }

    public void gameactivity() {
        Message msg = new Message();
        msg.what = 1;
        if (selectPattern == 1) {
            msg.obj = "EasyGame";
        } else if (selectPattern == 2) {
            msg.obj = "NormalGame";
        } else {
            msg.obj = "HardGame";
        }
        MainActivity.mhandler.sendMessage(msg);
    }

    private JSONObject initJsonbye() throws JSONException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("request","bye");
        return jsonObject;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //exit();
            new Thread(() -> {
                NetConn.writer.println(initJsonbye().toString());
            }).start();
            Intent intent = new Intent(StartGameActivity.this, LoginOrRegisterActivity.class);
            startActivity(intent);
            return false;
        }
        else {
            return super.onKeyDown(keyCode, event);
        }
    }
}
